package com.winit.openapi.gfs.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.spi.context.CommandContext;
import com.winit.gfs.spi.AutoDeliveryRuleService;
import com.winit.gfs.spi.EbayCurrencyService;
import com.winit.gfs.spi.EbayDeliveryWayRuleConfigService;
import com.winit.gfs.spi.EbaySiteConfigService;
import com.winit.gfs.spi.command.AutoDeliverySearchCommand;
import com.winit.gfs.spi.command.AutoDeliveryUpdateCommand;
import com.winit.gfs.spi.command.EbayDeliveryWayRuleConfigCommand;
import com.winit.gfs.spi.command.EbaySiteRuleConfigCommand;
import com.winit.gfs.spi.vo.AddresseeInfoRuleVo;
import com.winit.gfs.spi.vo.AutoDeliveryRuleVo;
import com.winit.gfs.spi.vo.EbayDeliveryWayRuleConfigVo;
import com.winit.gfs.spi.vo.EbayDeliveryWayRuleVo;
import com.winit.gfs.spi.vo.EbayInfoRuleVo;
import com.winit.gfs.spi.vo.EbayProductRuleVo;
import com.winit.gfs.spi.vo.EbaySiteConfigVo;
import com.winit.gfs.spi.vo.EbaySiteRuleVo;
import com.winit.gfs.spi.vo.GfsAutoDeliveryRuleVasAttrVo;
import com.winit.gfs.spi.vo.GfsAutoDeliveryRuleVasVo;
import com.winit.gfs.spi.vo.GfsEbayCurrencyVo;
import com.winit.mms.spi.v2.item.ItemService;
import com.winit.mms.spi.v2.item.command.QueryItemForAutoDeliveryCommand;
import com.winit.mms.spi.v2.item.vo.ItemVo;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.gfs.util.GfsCommonUtil;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.commnad.customer.QueryCompanylCommand;
import com.winit.ums.spi.vo.CustomerInfoVO;

/**
 * 自动发货规则控制类
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * hou 	1.0  		2015-8-10 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/gfs/deliveryrule")
public class AutoDeliveryRuleController extends BaseController {

    @Resource
    private AutoDeliveryRuleService          autoDeliveryRuleService;

    @Resource
    private EbaySiteConfigService            ebaySiteConfigService;

    @Resource
    private EbayDeliveryWayRuleConfigService ebayDeliveryWayRuleConfigService;
    
    @Resource
    private EbayCurrencyService ebayCurrencyService;
    
    //@Resource
    //private ProductService erpProductService;
    
    @Resource
    private ItemService                      itemService;

    @Resource
    private UmsCustomerService               umsCustomerService;
    
    /**
     * 查询自动发货规则记录
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/querylist")
    public String querylist(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        AutoDeliverySearchCommand command = new AutoDeliverySearchCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            Searchable<?> searchable = buildSearchablePageParamsByRule(json);
            if(ValidateUtil.isNotNull(json, "isactive"))
            {
                command.setIsactive(json.getString("isactive"));
            }
            command.setSearchable(searchable);
        } else if (obj == null || StringUtils.isBlank(obj.toString())) {
            Searchable<?> searchable = buildSearchablePageParamsByRule(null);
            command.setSearchable(searchable);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        // 调用接口分页查询规则
        Page<AutoDeliveryRuleVo> pagelist = autoDeliveryRuleService.queryAutoDelivery(command);
        if (pagelist != null) {
            Map<String, Object> data = getPageParams(pagelist);
            data.put("list", pagelist.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 查询自动发货规则记录
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/batchdelete")
    public String batchdelete(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        AutoDeliveryUpdateCommand command = new AutoDeliveryUpdateCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            if (json.containsKey("list")) {
                List<Long> ids = new ArrayList<Long>();
                JSONArray list = json.getJSONArray("list");
                for (Object o : list) {
                    JSONObject tmp = (JSONObject) o;
                    ids.add(tmp.getLong("id"));
                }
                command.setList(ids);
            } else {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        // 调用批量删除接口
        autoDeliveryRuleService.batchdeleteAutoDeliveryByRuleIds(command);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("code", 1);
        responseMsg.setData(data);
        return SUCCESS;
    }

    @RequestMapping(value = "/isactive")
    public String isactive(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        AutoDeliveryUpdateCommand command = new AutoDeliveryUpdateCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            AutoDeliveryRuleVo ruleVo = buildRuleParams(json,false);
            command.setRuleVo(ruleVo);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        // 调用修改优先级
        autoDeliveryRuleService.updateAutoDeliveryRule(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("code", 1);
        responseMsg.setData(data);
        return SUCCESS;
    }

    @RequestMapping(value = "/updateLevel")
    public String updateLevel(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        AutoDeliveryUpdateCommand command = new AutoDeliveryUpdateCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            AutoDeliveryRuleVo ruleVo = buildRuleParams(json,false);
            command.setRuleVo(ruleVo);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        // 调用修改优先级
        autoDeliveryRuleService.updateAutoDeliveryRule(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("code", 1);
        responseMsg.setData(data);
        return SUCCESS;
    }

    @RequestMapping(value = "/create")
    public String create(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        AutoDeliveryUpdateCommand command = new AutoDeliveryUpdateCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            AutoDeliveryRuleVo ruleVo = buildRuleParams(json,true);
            command.setRuleVo(ruleVo);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        // 调用创建
        Long id = autoDeliveryRuleService.addAutoDeliveryRule(command);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("id", id);
        data.put("code", 1);
        responseMsg.setData(data);
        return SUCCESS;
    }

    @RequestMapping(value = "/update")
    public String update(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        AutoDeliveryUpdateCommand command = new AutoDeliveryUpdateCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            AutoDeliveryRuleVo ruleVo = buildRuleParams(json,true);
            command.setRuleVo(ruleVo);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        // 调用修改
        autoDeliveryRuleService.updateAutoDeliveryRule(command);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("code", 1);
        responseMsg.setData(data);
        return SUCCESS;
    }

    @RequestMapping(value = "/query")
    public String query(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        AutoDeliveryUpdateCommand command = new AutoDeliveryUpdateCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            AutoDeliveryRuleVo ruleVo = buildRuleParams(json,false);
            command.setRuleVo(ruleVo);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        // 调用查询接口
        AutoDeliveryRuleVo vo = autoDeliveryRuleService.queryAutoDeliveryById(command);
        Map<Object, Object> data = buildMapByRuleVo(vo);
        responseMsg.setData(data);
        return SUCCESS;
    }

    @RequestMapping(value = "/siteQuerylist")
    public String siteQuerylist(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        EbaySiteRuleConfigCommand command = new EbaySiteRuleConfigCommand();
        command.setCtx(CommandContext.getContext());
        // 调用站点查询接口
        List<EbaySiteConfigVo> vos = ebaySiteConfigService.querySiteList(command);
        Map<Object, Object> data = new HashMap<Object, Object>();
        data.put("ebaysitelist", vos);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/queryCurrency")
    public String queryCurrency(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	List<GfsEbayCurrencyVo> vos = ebayCurrencyService.queryCurrency();
    	Map<Object, Object> data = new HashMap<Object, Object>();
        data.put("ebaysitelist", vos);
        responseMsg.setData(data);
    	return SUCCESS;
    }

    @RequestMapping(value = "/deliverywayQuerylist")
    public String deliverywayQuerylist(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        EbayDeliveryWayRuleConfigCommand command = new EbayDeliveryWayRuleConfigCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            if (json.containsKey("countryCode")) {
                command.setContryCode(json.getString("countryCode"));
            } else {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        // 调用查询接口
        List<EbayDeliveryWayRuleConfigVo> vos = ebayDeliveryWayRuleConfigService.queryDeliveryWayRuleList(command);
        Map<Object, Object> data = new HashMap<Object, Object>();
        data.put("deliverywaylist", vos);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/productCodeQuery")
    public String productCodeQuery(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        QueryItemForAutoDeliveryCommand command = new QueryItemForAutoDeliveryCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            String customerCode = json.getString("customerCode");
            if(StringUtils.isNotEmpty(customerCode)){
                command.setCustomerCode(customerCode);
            }else{
                //String cBPartnerId = command.getCtx().getUserId();
                QueryCompanylCommand userCommand = new QueryCompanylCommand();
                userCommand.setEmail(CommandContext.getContext().getUsername());
                // 获取客户编码
                CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
                if(customer!=null){
                    customerCode = customer.getCode();
                }else{
                    customerCode = command.getCtx().getUserId();
                }
                command.setCustomerCode(customerCode);
            }
            command.setSkuCode(json.getString("sku"));
            command.setGroupSkuCode(json.getString("groupSkuCode"));
            if(StringUtils.isEmpty(command.getSkuCode()) && StringUtils.isEmpty(command.getGroupSkuCode())){
                Map<Object, Object> data = new HashMap<Object, Object>();
                data.put("productList", Lists.newArrayList());
                responseMsg.setData(data);
                return SUCCESS;
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        // 调用查询接口
        //List<Product> list = erpProductService.queryProductByLikeValue(command);
        List<ItemVo> list = itemService.queryItemForAutoDelivery(command);
        List<Map<String,Object>> itemList = Lists.newArrayList();
        if(list!=null){
            for(ItemVo itemVo : list){
                Map<String,Object> rowMap = new HashMap<String,Object>();
                rowMap.put("sku", itemVo.getCode());
                rowMap.put("value", itemVo.getSkuCode());
                rowMap.put("name", itemVo.getCnName());
                rowMap.put("ename", itemVo.getName());
                rowMap.put("specification", itemVo.getSpecification());
                rowMap.put("url", itemVo.getInternetSite());
                rowMap.put("description", itemVo.getDescription());
                rowMap.put("isNew", itemVo.getIsNew());
                rowMap.put("length", itemVo.getLength());
                rowMap.put("width", itemVo.getWidth());
                rowMap.put("height", itemVo.getHeight());
                rowMap.put("weight", itemVo.getWeight());
                rowMap.put("volume", itemVo.getVolume());
                rowMap.put("sellerLength", itemVo.getRegisterLength());
                rowMap.put("sellerWidth", itemVo.getRegisterWidth());
                rowMap.put("sellerHeight", itemVo.getRegisterHeight());
                rowMap.put("sellerWeight", itemVo.getRegisterWeight());
                rowMap.put("sellerVolume", itemVo.getRegisterVolume());
                itemList.add(rowMap);
            }
        }
        Map<Object, Object> data = new HashMap<Object, Object>();
        data.put("productList", itemList);
        responseMsg.setData(data);
        return SUCCESS;
    }

    /**
     * 封装参数
     */
    private Map<Object, Object> buildMapByRuleVo(AutoDeliveryRuleVo vo) {
        Map<Object, Object> data = new HashMap<Object, Object>();
        data.put("id", vo.getId());
        data.put("ruleName", vo.getRuleName());
        data.put("deliveryType", vo.getDeliveryType());
        data.put("deliveryWay", vo.getDeliveryWay());
        data.put("warehouse", vo.getWarehouse());
        data.put("minLength", vo.getMinLength());
        data.put("minWidth", vo.getMinWidth());
        data.put("minHeight", vo.getMinHeight());
        data.put("minVolume", vo.getMinVolume());
        data.put("minWeight", vo.getMinWeight());
        data.put("maxLength", vo.getMaxLength());
        data.put("maxWidth", vo.getMaxWidth());
        data.put("maxHeight", vo.getMaxHeight());
        data.put("maxVolume", vo.getMaxVolume());
        data.put("maxWeight", vo.getMaxWeight());
        data.put("minBuyerPayprice", vo.getMinBuyerPayprice());
        data.put("maxBuyerPayprice", vo.getMaxBuyerPayprice());
        data.put("buyerPaycurrency", vo.getBuyerPaycurrency());
        data.put("minOrderTotalprice", vo.getMinOrderTotalprice());
        data.put("maxOrderTotalprice", vo.getMaxOrderTotalprice());
        data.put("orderTotalcurrency", vo.getOrderTotalcurrency());
        data.put("deliveryCountry", vo.getDeliveryCountry());
        data.put("ebayselleridlist", vo.getEbayinfoRuleList());
        data.put("ebaysitelist", vo.getEbaysiteList());
        data.put("addresseelist", vo.getAddresseeinfoList());
        data.put("productlist", vo.getEbayproductList());
        data.put("options", vo.getOptions());
        data.put("egdOrder", vo.getEgdOrder());
        data.put("deliverywaylist", vo.getEbaydeliveryWayList());
        
        data.put("winitProduct", vo.getWinitProduct());
        data.put("shipperAddrCode", vo.getShipperAddrCode());
        data.put("winitwarehouse", vo.getWinitwarehouse());
        data.put("dispatchType", vo.getDispatchType());
        data.put("productMsg", vo.getProductMsg());
        data.put("vasList", vo.getVasList());
        return data;
    }

    /**
     * 解析参数
     * 
     * @param json
     * @return
     */
    private AutoDeliveryRuleVo buildRuleParams(JSONObject json,boolean isvalid) {
        AutoDeliveryRuleVo vo = new AutoDeliveryRuleVo();
        if (ValidateUtil.isNotNull(json, "id")) {
            ValidateUtil.validInteger(json, "id");
            vo.setId(json.getLong("id"));
        }
        if (ValidateUtil.isNotNull(json, "isactive")) {
            ValidateUtil.validMaxLength(json, "isactive", 10);
            vo.setIsactive(json.getString("isactive"));
        }
        if (ValidateUtil.isNotNull(json, "ruleNo")) {
            ValidateUtil.validInteger(json, "ruleNo");
            ValidateUtil.validNotNegativeNumber(json, "ruleNo");
            vo.setRuleNo(json.getLong("ruleNo"));
        }
        if(isvalid)
        {
            ValidateUtil.validNotNull(json, "ruleName");
            ValidateUtil.validMaxLength(json, "ruleName", 250);
            vo.setRuleName(json.getString("ruleName"));
            
            ValidateUtil.validNotNull(json, "deliveryType");
            ValidateUtil.validMaxLength(json, "deliveryType", 10);
            vo.setDeliveryType(json.getString("deliveryType"));
            
            if("S".equals(vo.getDeliveryType())){
            	ValidateUtil.validNotNull(json, "deliveryWay");
                ValidateUtil.validMaxLength(json, "deliveryWay", 10);
                vo.setDeliveryWay(json.getString("deliveryWay"));
            	
            	ValidateUtil.validNotNull(json, "deliveryWayName");
                ValidateUtil.validMaxLength(json, "deliveryWayName", 100);
                vo.setDeliveryWayName(json.getString("deliveryWayName"));
                
                ValidateUtil.validNotNull(json, "warehouse");
                ValidateUtil.validMaxLength(json, "warehouse", 100);
                vo.setWarehouse(json.getString("warehouse"));
                
                ValidateUtil.validNotNull(json, "warehouseName");
                ValidateUtil.validMaxLength(json, "warehouseName", 100);
                vo.setWarehouseName(json.getString("warehouseName"));
            }else{

                ValidateUtil.validNotNull(json, "dispatchType");
                ValidateUtil.validMaxLength(json, "dispatchType", 100);
                vo.setDispatchType(json.getString("dispatchType"));
            	
            	ValidateUtil.validNotNull(json, "dispatchTypeName");
                ValidateUtil.validMaxLength(json, "dispatchTypeName", 100);
                vo.setDeliveryWayName(json.getString("dispatchTypeName"));
                
                ValidateUtil.validNotNull(json, "winitProductCode");
                ValidateUtil.validMaxLength(json, "winitProductCode", 100);
                vo.setWinitProduct(json.getString("winitProductCode"));
                
                ValidateUtil.validNotNull(json, "winitProductName");
                ValidateUtil.validMaxLength(json, "winitProductName", 100);
                vo.setWinitProductName(json.getString("winitProductName"));
                
                ValidateUtil.validNotNull(json, "shipperAddrCode");
                ValidateUtil.validMaxLength(json, "shipperAddrCode", 100);
                vo.setShipperAddrCode(json.getString("shipperAddrCode"));
                
                ValidateUtil.validNotNull(json, "winitwarehouse");
                ValidateUtil.validMaxLength(json, "winitwarehouse", 100);
                vo.setWinitwarehouse(json.getString("winitwarehouse"));
                
                ValidateUtil.validNotNull(json, "winitwarehouseName");
                ValidateUtil.validMaxLength(json, "winitwarehouseName", 100);
                vo.setWinitwarehouseName(json.getString("winitwarehouseName"));
                
                ValidateUtil.validNotNull(json, "productMsg");
                ValidateUtil.validMaxLength(json, "productMsg", 100);
                vo.setProductMsg(json.getString("productMsg"));
            }
            
            if (ValidateUtil.isNotNull(json, "minLength")) {
                ValidateUtil.validNotNegativeNumber(json, "minLength");
                ValidateUtil.validBigDecimal(json, "minLength");
                ValidateUtil.validatePrecision(json, "minLength", 10, 2);
                vo.setMinLength(json.getBigDecimal("minLength"));
            }
            if (ValidateUtil.isNotNull(json, "minWidth")) {
                ValidateUtil.validNotNegativeNumber(json, "minWidth");
                ValidateUtil.validBigDecimal(json, "minWidth");
                ValidateUtil.validatePrecision(json, "minWidth", 10, 2);
                vo.setMinWidth(json.getBigDecimal("minWidth"));
            }
            if (ValidateUtil.isNotNull(json, "minHeight")) {
                ValidateUtil.validNotNegativeNumber(json, "minHeight");
                ValidateUtil.validBigDecimal(json, "minHeight");
                ValidateUtil.validatePrecision(json, "minHeight", 10, 2);
                vo.setMinHeight(json.getBigDecimal("minHeight"));
            }
            if (ValidateUtil.isNotNull(json, "minVolume")) {
                ValidateUtil.validNotNegativeNumber(json, "minVolume");
                ValidateUtil.validBigDecimal(json, "minVolume");
                ValidateUtil.validatePrecision(json, "minVolume", 10, 6);
                vo.setMinVolume(json.getBigDecimal("minVolume"));
            }
            if (ValidateUtil.isNotNull(json, "minWeight")) {
                ValidateUtil.validNotNegativeNumber(json, "minWeight");
                ValidateUtil.validBigDecimal(json, "minWeight");
                ValidateUtil.validatePrecision(json, "minWeight", 10, 4);
                vo.setMinWeight(json.getBigDecimal("minWeight"));
            }
            if (ValidateUtil.isNotNull(json, "maxLength")) {
                ValidateUtil.validNotNegativeNumber(json, "maxLength");
                ValidateUtil.validBigDecimal(json, "maxLength");
                ValidateUtil.validatePrecision(json, "maxLength", 10, 2);
                vo.setMaxLength(json.getBigDecimal("maxLength"));
            }
            if (ValidateUtil.isNotNull(json, "maxWidth")) {
                ValidateUtil.validNotNegativeNumber(json, "maxWidth");
                ValidateUtil.validBigDecimal(json, "maxWidth");
                ValidateUtil.validatePrecision(json, "maxWidth", 10, 2);
                vo.setMaxWidth(json.getBigDecimal("maxWidth"));
            }
            if (ValidateUtil.isNotNull(json, "maxHeight")) {
                ValidateUtil.validNotNegativeNumber(json, "maxHeight");
                ValidateUtil.validBigDecimal(json, "maxHeight");
                ValidateUtil.validatePrecision(json, "maxHeight", 10, 2);
                vo.setMaxHeight(json.getBigDecimal("maxHeight"));
            }
            if (ValidateUtil.isNotNull(json, "maxVolume")) {
                ValidateUtil.validNotNegativeNumber(json, "maxVolume");
                ValidateUtil.validBigDecimal(json, "maxVolume");
                ValidateUtil.validatePrecision(json, "maxVolume", 10, 6);
                vo.setMaxVolume(json.getBigDecimal("maxVolume"));
            }
            if (ValidateUtil.isNotNull(json, "maxWeight")) {
                ValidateUtil.validNotNegativeNumber(json, "maxWeight");
                ValidateUtil.validBigDecimal(json, "maxWeight");
                ValidateUtil.validatePrecision(json, "maxWeight", 10, 4);
                vo.setMaxWeight(json.getBigDecimal("maxWeight"));
            }
            if (ValidateUtil.isNotNull(json, "minBuyerPayprice")) {
                ValidateUtil.validNotNegativeNumber(json, "minBuyerPayprice");
                ValidateUtil.validBigDecimal(json, "minBuyerPayprice");
                ValidateUtil.validatePrecision(json, "minBuyerPayprice", 10, 2);
                vo.setMinBuyerPayprice(json.getBigDecimal("minBuyerPayprice"));
            }
            if (ValidateUtil.isNotNull(json, "maxBuyerPayprice")) {
                ValidateUtil.validNotNegativeNumber(json, "maxBuyerPayprice");
                ValidateUtil.validatePrecision(json, "maxBuyerPayprice", 10, 2);
                vo.setMaxBuyerPayprice(json.getBigDecimal("maxBuyerPayprice"));
            }
            if (ValidateUtil.isNotNull(json, "buyerPaycurrency")) {
                ValidateUtil.validMaxLength(json, "buyerPaycurrency", 10);
                vo.setBuyerPaycurrency(json.getString("buyerPaycurrency"));
            }
            if (ValidateUtil.isNotNull(json, "minOrderTotalprice")) {
                ValidateUtil.validNotNegativeNumber(json, "minOrderTotalprice");
                ValidateUtil.validatePrecision(json, "minOrderTotalprice", 10, 2);
                vo.setMinOrderTotalprice(json.getBigDecimal("minOrderTotalprice"));
            }
            if (ValidateUtil.isNotNull(json, "maxOrderTotalprice")) {
                ValidateUtil.validNotNegativeNumber(json, "maxOrderTotalprice");
                ValidateUtil.validatePrecision(json, "maxOrderTotalprice", 10, 2);
                vo.setMaxOrderTotalprice(json.getBigDecimal("maxOrderTotalprice"));
            }
            if (ValidateUtil.isNotNull(json, "orderTotalcurrency")) {
                ValidateUtil.validMaxLength(json, "orderTotalcurrency", 100);
                vo.setOrderTotalcurrency(json.getString("orderTotalcurrency"));
            }
            if (ValidateUtil.isNotNull(json, "deliveryCountry")) {
                ValidateUtil.validMaxLength(json, "deliveryCountry", 100);
                vo.setDeliveryCountry(json.getString("deliveryCountry"));
            }
            if (ValidateUtil.isNotNull(json, "options")){
            	vo.setOptions(json.getString("options"));
            }
            if (ValidateUtil.isNotNull(json, "egdOrder")){
                vo.setEgdOrder(json.getString("egdOrder"));
            }
            
            buildEbaySellerIdList(json, vo);
            
            buildEbaySiteList(json, vo);
            
            buildAddresseeInfoList(json, vo);
            
            buildProductList(json, vo);
            
            buildDeliveryList(json, vo);
            
            buildVasAndAttr(vo,json);
        }
        return vo;
    }
    
    private void buildVasAndAttr(AutoDeliveryRuleVo vo,JSONObject tobj){
        // vas
        JSONArray vasJsonList = tobj.getJSONArray("vasList");
        if(vasJsonList != null && vasJsonList.size() > 0){
            List<GfsAutoDeliveryRuleVasVo> vasVoList = new ArrayList<GfsAutoDeliveryRuleVasVo>();
            for(Object o1:vasJsonList){
                JSONObject vasJson = (JSONObject) o1;
                GfsAutoDeliveryRuleVasVo vasVo = new GfsAutoDeliveryRuleVasVo();
                vasVo.setServiceCode(vasJson.getString("serviceCode"));
                vasVo.setServiceName(vasJson.getString("serviceName"));
                vasVoList.add(vasVo);
                JSONArray vasAttrVoJsonList = vasJson.getJSONArray("vasAttrList");
                if(vasAttrVoJsonList != null && vasAttrVoJsonList.size() > 0){
                    List<GfsAutoDeliveryRuleVasAttrVo> vasArrtVoList = new ArrayList<GfsAutoDeliveryRuleVasAttrVo>();
                    for(Object o2:vasAttrVoJsonList){
                        JSONObject vasAttrJson = (JSONObject) o2;
                        GfsAutoDeliveryRuleVasAttrVo vasAttrVo = new GfsAutoDeliveryRuleVasAttrVo();
                        vasAttrVo.setAttrKey(vasAttrJson.getString("attrKey"));
                        vasAttrVo.setAttrName(vasAttrJson.getString("attrName"));
                        vasAttrVo.setAttrValue(vasAttrJson.getString("attrValue"));
                        vasArrtVoList.add(vasAttrVo);
                    }
                    vasVo.setVasAttrList(vasArrtVoList);
                }
            }
            vo.setVasList(vasVoList);
        }
    }

    private void buildDeliveryList(JSONObject json, AutoDeliveryRuleVo vo) {
        if (ValidateUtil.isNotNull(json, "deliverywaylist")) {
            JSONArray list = json.getJSONArray("deliverywaylist");
            List<EbayDeliveryWayRuleVo> elist = new ArrayList<EbayDeliveryWayRuleVo>();
            for (Object o : list) {
                JSONObject tmp = (JSONObject) o;
                EbayDeliveryWayRuleVo tvo = new EbayDeliveryWayRuleVo();
                tvo.setDeliverywayId(tmp.getLong("deliverywayId"));
                tvo.setDeliveryName(tmp.getString("deliveryName"));
                elist.add(tvo);
            }
            vo.setEbaydeliveryWayList(elist);
        }
    }

    private void buildProductList(JSONObject json, AutoDeliveryRuleVo vo) {
        if (ValidateUtil.isNotNull(json, "productlist")) {
            JSONArray list = json.getJSONArray("productlist");
            List<EbayProductRuleVo> elist = new ArrayList<EbayProductRuleVo>();
            for (Object o : list) {
                JSONObject tmp = (JSONObject) o;
                EbayProductRuleVo tvo = new EbayProductRuleVo();
                tvo.setProductId(tmp.getLong("productId"));
                tvo.setSku(tmp.getString("sku"));
                tvo.setProductName(tmp.getString("productName"));
                tvo.setProductNameEn(tmp.getString("productNameEn"));
                if(ValidateUtil.isNotNull(tmp, "minNum"))
                {
                    ValidateUtil.validInteger(tmp, "minNum");
                    ValidateUtil.validNotNegativeNumber(tmp, "minNum");
                    tvo.setMinNum(tmp.getIntValue("minNum"));
                }
                
                if(ValidateUtil.isNotNull(tmp, "maxNum"))
                {
                    ValidateUtil.validInteger(tmp, "maxNum");
                    ValidateUtil.validNotNegativeNumber(tmp, "maxNum");
                    tvo.setMaxNum(tmp.getIntValue("maxNum"));
                }
                elist.add(tvo);
            }
            vo.setEbayproductList(elist);
        }
    }

    private void buildAddresseeInfoList(JSONObject json, AutoDeliveryRuleVo vo) {
        if (ValidateUtil.isNotNull(json, "addresseelist")) {
            JSONArray list = json.getJSONArray("addresseelist");
            List<AddresseeInfoRuleVo> elist = new ArrayList<AddresseeInfoRuleVo>();
            for (Object o : list) {
                JSONObject tmp = (JSONObject) o;
                AddresseeInfoRuleVo tvo = new AddresseeInfoRuleVo();
                
                ValidateUtil.validMaxLength(tmp, "countryCode", 100);
                tvo.setCountryCode(tmp.getString("countryCode"));
                
                ValidateUtil.validMaxLength(tmp, "state", 100);
                tvo.setState(tmp.getString("state"));
                
                ValidateUtil.validMaxLength(tmp, "city", 100);
                tvo.setCity(tmp.getString("city"));
                
                ValidateUtil.validMaxLength(tmp, "postalcode", 100);
                tvo.setPostalcode(tmp.getString("postalcode"));
                tvo.setRuleType(tmp.getString("ruleType"));
                elist.add(tvo);
            }
            vo.setAddresseeinfoList(elist);
        }
    }

    private void buildEbaySiteList(JSONObject json, AutoDeliveryRuleVo vo) {
        if (ValidateUtil.isNotNull(json, "ebaysitelist")) {
            JSONArray list = json.getJSONArray("ebaysitelist");
            List<EbaySiteRuleVo> elist = new ArrayList<EbaySiteRuleVo>();
            for (Object o : list) {
                JSONObject tmp = (JSONObject) o;
                EbaySiteRuleVo tvo = new EbaySiteRuleVo();
                tvo.setEbaySiteId(tmp.getLong("ebaySiteId"));
                tvo.setEbaySiteName(tmp.getString("ebaySiteName"));
                elist.add(tvo);
            }
            vo.setEbaysiteList(elist);
        }
    }

    private void buildEbaySellerIdList(JSONObject json, AutoDeliveryRuleVo vo) {
        if (ValidateUtil.isNotNull(json, "ebayselleridlist")) {
            JSONArray list = json.getJSONArray("ebayselleridlist");
            List<EbayInfoRuleVo> elist = new ArrayList<EbayInfoRuleVo>();
            for (Object o : list) {
                JSONObject tmp = (JSONObject) o;
                EbayInfoRuleVo tvo = new EbayInfoRuleVo();
                tvo.setEbaySellerid(tmp.getString("ebaySellerid"));
                tvo.setEbayAccountId(tmp.getLong("ebayAccountId"));
                elist.add(tvo);
            }
            vo.setEbayinfoRuleList(elist);
        }
    }

    private Searchable<?> buildSearchablePageParamsByRule(JSONObject json) {
        String sort = "desc";
        String sortColumn = "RULE_NO";
        Searchable<?> search = GfsCommonUtil.buildSearchablePageParams(json);
        // pageParams
        if (isExistValue(json, "pageParams")) {
            JSONObject pageParams = json.getJSONObject("pageParams");
            if (!ValidateUtil.isNullOrEmpty(pageParams.getString("sort")) && !ValidateUtil.isNullOrEmpty(pageParams.getString("sortColumn"))) {
                sort = pageParams.getString("sort");
                sortColumn = pageParams.getString("sortColumn");
                if (!"asc".equalsIgnoreCase(sort) && !"desc".equalsIgnoreCase(sort)) {
                    throw new ApiException(ErrorCode.FIELD_ERROR, "sort");
                }

                if("isactive".equals(sortColumn))
                {
                    sortColumn = "ISACTIVE";
                }
                else if("ruleName".equals(sortColumn))
                {
                    sortColumn = "RULE_NAME";
                }
                else if("ruleNo".equals(sortColumn))
                {
                    sortColumn = "RULE_NO";
                }else
                {
                	sortColumn = "DELIVERY_TYPE";
                }
            }
        }
        //排序方式
        Direction direction = Direction.DESC;
        if ("asc".equalsIgnoreCase(sort))
        {
            direction = Direction.ASC;
        }
        search.addSort(new Sort(direction, sortColumn));
        return search;
    }
}
